import { createApp } from 'app/config/app'

const isContext = process.env.NODE_ENV !=='work'

export default (context)=>{
  return new Promise((resolve, reject) => {
		const s = isContext && Date.now();
		const { app, router, store } = createApp();
		//设置服务器端 router的位置
		const {url} = context;
		const fullPath = router.resolve(url).route.fullPath;
		
		if(fullPath !== url){
			reject({url:fullPath})
		}
		
		router.push(url)
    router.onReady(() => {
      const matchedComponents = router.getMatchedComponents()
      if (!matchedComponents.length) {
        reject({ code: 404 })
      }
      Promise.all(matchedComponents.map(({ asyncData }) => asyncData && asyncData({
        store,
        route: router.currentRoute
      }))).then(() => {
        isContext && console.log(`data pre-fetch: ${Date.now() - s}ms`)
        context.state = store.state
        resolve(app)
      }).catch(reject)
    }, reject)
	})
}
